<template>
  <div class="pl-[20px] pt-[2px] pb-[2px]">
    <el-tag
      size="default"
      v-for="(item, index) in tags"
      :key="item.path"
      :effect="item.title == router.meta.title ? 'dark' : 'plain'"
      class="mx-1 cursor-pointer mr-[3px]"
      @click="goTo(item.path)"
      @close="close(index)"
      :disable-transitions="true"
      :closable="tags.length > 1"
    >
      <i
        class="w-2 h-2 mr-[4px] bg-white inline-block rounded-full"
        v-show="item.title == router.meta.title"
      ></i>
      {{ item.title }}
    </el-tag>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import baseRouter from '@/router'

const router = useRoute()

let tags: any = ref([])
//监听路由变化
watch(
  () => router.path,
  () => {
    const boolean = tags.value.find((item: any) => {
      return router.path == item.path
    })
    if (!boolean) {
      tags.value.push({
        title: router.meta.title,
        path: router.path,
      })
    }
  },
  { immediate: true }
)

// 切换
const goTo = (path: string) => {
  baseRouter.replace({ path: path })
}

const close = (index: number) => {
  // 跳转到最后一项
  if (tags.value[index].path === router.path && index != tags.length - 1) {
    console.log(1)

    baseRouter.replace({ path: tags.value[tags.value.length - 2].path })
  }
  // 关闭当前项，本质上就是删除tags的对应项
  tags.value.splice(index, 1)
}
</script>

<style scoped></style>
